package DBD::Yahoo::st;

use strict;
use base qw(DBD::_::st);
use vars qw($VERSION $imp_data_size);

use DBI;

$VERSION       = "0.01";
$imp_data_size = 0;

sub bind_param
{
  my $sth = shift;
  my $pos = shift;
  my $val = shift;
  $sth->{'input'} = $val;
}

sub execute
{
  my $sth = shift;
  my $val = shift;
  $sth->{'input'} = $val if $val;

  # The Yahoo::Search instance
  my $yahoo = $sth->{'YahooSearch'};

  # The names of the columns in which we are interested
  my @columns = @{$sth->{'Columns'}};

  my $space = $sth->{'Space'};
  my $query = $sth->{'Query'};
  $query = $sth->{'input'} if $query eq '?';

  # This executes the search
  my @results = $yahoo->Results(
    $space  => $query,
    'Count' => $sth->{'Count'},
    'Start' => $sth->{'Start'},
  );

  my @new_columns;
  foreach my $column (@columns)
  {
    if ($column eq '*')
    {
      my %_data = $results[0]->Data;
      map { push(@new_columns, uc $_); } keys %_data;
    }
    else
    {
      push(@new_columns, $column);
    }
  }
  @columns = @new_columns;
  $sth->{'Columns'} = \@columns;

  my @data;
  foreach my $result (@results)
  {
    my %_data = $result->Data;
    my $lcdata;
    foreach my $_key (keys %_data)
    {
      my $lckey = lc $_key;
      $lcdata->{$lckey} = $_data{$_key} if !exists($lcdata->{$lckey});
    }
    my @this;
    foreach my $column (@columns)
    {
      my $lckey = lc $column;
      push(@this, $lcdata->{$lckey}) if $lckey eq '*' or exists($lcdata->{$lckey});
    }
    push @data, \@this;
  }

  $sth->{'driver_data'} = \@data;
  $sth->{'driver_rows'} = @data;
  $sth->STORE('NUM_OF_FIELDS', scalar @columns);

  return scalar @data || '0E0';
}

sub fetchrow_arrayref
{
  my $sth = shift;
  my $data = $sth->FETCH('driver_data');
  my $row = shift @$data or return;
  return $sth->_set_fbav($row);
}
*fetch = *fetch = \&fetchrow_arrayref;

sub fetchrow_hashref {
  my $sth      = shift;
  my @columns = @{$sth->{'Columns'}};
  my $data = $sth->FETCH('driver_data');
  my $row = shift @$data or return;
  my %rowhash;
  @rowhash{ @columns } = @$row;
  return \%rowhash;
}

sub rows
{
  my $sth = shift;
  return $sth->FETCH('driver_rows');
}

# Returns available tables
sub table_info { return "Yahoo" }

1;

sub DESTROY { 1 }

__END__
